package de.toolschmied.jjas.client.widgets;

import java.util.LinkedList;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ToggleButton;

import de.toolschmied.jjas.client.cms.actions.SelectableType;

public class SelectionBar<T extends SelectableType> extends Composite {
	
	public interface SelectionListener<T> {
		
		public void selectionChanged(T element);
		
	}
	
	private final ToggleHandler clickHandler = new ToggleHandler();
	private final LinkedList<SelectionListener<T>> listeners = new LinkedList<SelectionBar.SelectionListener<T>>();
	private final LinkedList<ToggleButton> buttons = new LinkedList<ToggleButton>();
	private final HorizontalPanel panel = new HorizontalPanel();	
	
	private final T[] elements;
	
	private T selected = null;
	
	public SelectionBar(T[] elements, T selected) {
		this.elements = elements;
		this.selected = selected;
		
		for (T element : elements) {
			createButton(element);
		}
		
		initWidget(panel);
	}

	private void createButton(T element) {
		String imageURL = element.getButtonImageURL();
		Image image = new Image(imageURL);
		
		ToggleButton button = new ToggleButton(image);
		button.addClickHandler(clickHandler);
		buttons.add(button);
		
		panel.add(button);
	}
	
	public T getSelection() {
		return selected;
	}
	
	public void setSelection(T t) {
		this.selected = t;
		
		for (int i = 0; i < elements.length; i++) {
			ToggleButton  button = buttons.get(i);
			T element = elements[i];
			button.setDown(selected == element);
		}
	}
	
	public void addSelectionListener(SelectionListener<T> selectionListener) {
		listeners.add(selectionListener);
	}

	public void removeSelectionListener(SelectionListener<T> listener) {
		listeners.remove(listener);
	}

	private void buttonSelected(ToggleButton button) {
		int index = buttons.indexOf(button);
		this.selected = elements[index];
		
		setSelection(selected);
		
		for (SelectionListener<T> listener : listeners) {
			listener.selectionChanged(selected);
		}
	}
	
	private class ToggleHandler implements ClickHandler {

		@Override
		public void onClick(ClickEvent event) {
			buttonSelected((ToggleButton) event.getSource());
		}
		
	}
	
}
